import axios from "axios";

const DB_NAME = "jnks-indexeddb-model";
const DB_VERSION = 1; // Use a long  for this value (don't use a float)
const DB_STORE_NAME = "model_gltf";

// 加载数据库
function initDb() {
  if (!window.indexedDB) {
    // ("您的浏览器不支持indexeddb");
    return;
  }

  let request = indexedDB.open(DB_NAME, DB_VERSION);

  return new Promise((resolve, reject) => {
    request.onerror = function () {
      // "创建失败");
      reject();
    };
    request.onupgradeneeded = function (evt) {
      evt.currentTarget.result.createObjectStore(DB_STORE_NAME, {
        keyPath: "ssn",
      });
    };
    request.onsuccess = function (evt) {
      // "创建成功");
      resolve(evt.target.result);
    };
  });
}

// 获取模型
async function getModel(url, id) {
  let db = await initDb();
  let getRequest = db
    .transaction([DB_STORE_NAME], "readwrite")
    .objectStore(DB_STORE_NAME)
    .get(id);
  return new Promise((resolve, reject) => {
    getRequest.onsuccess = function (event) {
      let modelFile = event.target.result;
      // 假如已经有缓存了 直接用缓存
      if (modelFile) {
        resolve(modelFile.blob);
      } else {
        // 假如没有缓存 请求新的模型存入
        inputModel(url, id)
          .then((blob) => {
            resolve(blob);
          })
          .catch(() => {
            reject();
          });
      }
    };
    getRequest.onerror = function (event) {
      // "error", event);
      reject();
    };
  });
}

// 存入模型
async function inputModel(url, id) {
  let db = await initDb();
  let modelResult = await axios.get(url, {
    responseType: "blob",
    onDownloadProgress: (e) => {
      if (id === 1) {
        window.dispatchEvent(
          new CustomEvent("loadingProgress", {
            detail: ((e.loaded * 100) / e.total).toFixed(2),
          })
        );
      }
    },
  });
  if (modelResult.status === 200) {
    let obj = {
      ssn: id,
    };
    obj.blob = new Blob([modelResult.data]);
    let inputRequest = db
      .transaction([DB_STORE_NAME], "readwrite")
      .objectStore(DB_STORE_NAME)
      .add(obj);
    return new Promise((resolve, reject) => {
      inputRequest.onsuccess = function () {
        // "数据添加成功");
        resolve(obj.blob);
      };
      inputRequest.onerror = function (evt) {
        // "数据添加失败", evt);
        reject();
      };
    });
  }
}

export { getModel, inputModel };
